package cn.lopr.im.android.utils;


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * http client
 *
 * @author shuangyang7
 * @date 2020/12/28 17:07
 */
public class HttpUtils {
    private static final android.os.Handler handler = new android.os.Handler();

    public static void doGetForResult(String url, OnRequestResult listener) {
        doGetForResult(url, (String) null, null, listener);
    }

    public static void doGetForResult(String url, String param, OnRequestResult listener) {
        doGetForResult(url, param, null, listener);
    }

    public static void doGetForResult(String url, Map<String, String> params, OnRequestResult listener) {
        StringBuilder urlBuilder = new StringBuilder();

        if (params != null && params.size() != 0) {
            urlBuilder.append("?");

            for (String key : params.keySet()) {
                String value = params.get(key);
                urlBuilder.append(key).append("=").append(value).append("&");
            }
        }

        String paramString = urlBuilder.toString();

        doGetForResult(url, paramString, null, listener);
    }

    /**
     * 发送get请求
     *
     * @param url      请求链接
     * @param params   请求参数
     * @param listener 监听器，用于回调
     * @author shuangyang7
     * @date 2021/1/1 16:33
     */
    public static void doGetForResult(String url, String params, String auth, OnRequestResult listener) {

        if (!TextUtils.isEmpty(params)) {
            url += params;
        }

        Request request = null;
        if (TextUtils.isEmpty(auth)) {
            request = new Request.Builder().url(url).build();
        } else {
            request = new Request.Builder().url(url).addHeader("Authorization", auth).build();
        }

        OkHttpClient.getInstance().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("HttpUtils: ", "onFailure: " + e);
                handler.post(() -> {
                    if (listener != null) {
                        listener.onResult("");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String data = "";
                if (Objects.requireNonNull(response).isSuccessful()) {
                    data = response.body() != null ? response.body().string() : null;
                }
                Objects.requireNonNull(call).cancel();
                final String result = data;
                handler.post(() -> {
                    if (listener != null) {
                        listener.onResult(result);
                    }
                });
            }
        });
    }

    /**
     * post 必须json 格式
     *
     * @author shuangyang7
     * @date 2020/12/30 11:09
     */
    public static void doPostForResult(String url, Map<String, Object> params, String token, OnRequestResult listener) {
        doPostForResult(url, GsonUtil.objectToJson(params), token, listener);
    }

    /**
     * post 必须json 格式
     *
     * @author shuangyang7
     * @date 2020/12/30 11:09
     */
    public static void doPostForResult(String url, Object params, String token, OnRequestResult listener) {
        doPostForResult(url, GsonUtil.objectToJson(params), token, listener);
    }

    public static void doPostForResult(String url, String params, String auth, OnRequestResult listener) {

        MediaType mediaType = MediaType.parse("application/json");
        RequestBody requestBody = RequestBody.create(mediaType, params);

        Request request = new Request.Builder().post(requestBody).url(url).build();
        if (TextUtils.isEmpty(auth)) {
            request = new Request.Builder().post(requestBody).url(url).build();
        } else {
            request = new Request.Builder().post(requestBody).url(url).addHeader("Authorization", auth).build();
        }

        OkHttpClient.getInstance().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.post(() -> {
                    if (listener != null) {
                        listener.onResult("");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String data = "";
                if (Objects.requireNonNull(response).isSuccessful()) {
                    data = response.body() != null ? response.body().string() : null;
                }
                Objects.requireNonNull(call).cancel();
                final String result = data;
                handler.post(() -> {
                    if (listener != null)
                        listener.onResult(result);
                });
            }
        });
    }

    public static Bitmap getHttpBitmap(String url) {

        URL myFileURL;
        Bitmap bitmap = null;
        try {
            myFileURL = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) myFileURL.openConnection();
            conn.setConnectTimeout(6000);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            InputStream is = conn.getInputStream();

            bitmap = BitmapFactory.decodeStream(is);

            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    public interface OnRequestResult {
        void onResult(String data);
    }
}
